//
//  UILabel+Align.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-9-11.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "UILabel+VerticalAlignment.h"
#import "NSObject+Associative.h"
#import "Utils_Swizzing.h"

const char verticalAlignmentKey;

static void (*oldDrawTextInRect)(id self,SEL _cmd,CGRect rect);
static void newDrawTextInRect(UILabel *self,SEL _cmd,CGRect rect)
{
    if (![self.text isKindOfClass:[NSString class]])
    {
        return;
    }
    CGRect actualRect = [self textRectForBounds:rect
                         limitedToNumberOfLines:self.numberOfLines];
    objc_runOldMethod([UILabel class],oldDrawTextInRect,self,_cmd,actualRect);
}




static CGRect (*oldTextRectForBoundsLimitedToNumberOfLines)(id self,
                                                          SEL _cmd,
                                                          CGRect bounds,
                                                          NSInteger lines);
static CGRect newTextRectForBoundsLimitedToNumberOfLines(UILabel *self,
                                                         SEL _cmd,
                                                         CGRect bounds,
                                                         NSInteger lines)
{
    CGRect textRect = objc_runOldMethod([UILabel class],oldTextRectForBoundsLimitedToNumberOfLines,self,_cmd,bounds,lines);
    switch (self.verticalAlignment) {
        case VerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case VerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case VerticalAlignmentMiddle:
            // Fall through.
        default:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
    }
    return textRect;
}

@implementation UILabel(VerticalAlignment)

+ (void)load
{
   oldTextRectForBoundsLimitedToNumberOfLines =
    objc_changeMethod(self,
                      @selector(textRectForBounds:limitedToNumberOfLines:),
                      newTextRectForBoundsLimitedToNumberOfLines);
    
    oldDrawTextInRect = objc_changeMethod(self, @selector(drawTextInRect:), newDrawTextInRect);
}


- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {

    [self setRetainNonatomicProperty:[NSNumber numberWithInteger:verticalAlignment]
                               byKey:&verticalAlignmentKey];
    [self setNeedsDisplay];
}

- (VerticalAlignment)verticalAlignment
{
    NSNumber *number = [self getAssociativeValue:&verticalAlignmentKey];
    if (number)
    {
        return number.integerValue;
    }
    else
    {
        return VerticalAlignmentMiddle;
    }
}

@end
